﻿using BLL;
using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using Utility.Helper;

namespace Thksoft.Module.ApplyView
{
    /// <summary>
    /// ApplyHandler 的摘要说明
    /// </summary>
    public class ApplyHandler : IHttpHandler, IRequiresSessionState
    {
        private Sys_User loginuser;

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType != "POST")
            {
                context.Response.ContentType = "text/plain";
                return;
            }

            {
                var Request = context.Request;
                var Response = context.Response;

                if (Request.Params.Get("userid") != null)
                {
                    loginuser = new Sys_UserBLL().GetInfoById(Request.Params["userid"].ToString());
                }

                switch (Request.Params.Get("MethodType"))
                {
                    case "SubmitApplay":
                        {
                            SubmitApplay(context);
                            return;
                        }
                    case "Save":
                        {
                            Save(context);
                            return;
                        }
                    case "Get":
                        {
                            Get(context);
                            return;
                        }
                    case "AllCompanyInfo":
                        {
                            GetAllCompany(context);
                            return;
                        }
                    default:
                        return;
                }
            }
        }

        #region MyRegion

        protected Sys_User GetCurrentUser()
        {
            return loginuser;
        }

        /// <summary>
        /// 获取当前请求的数据包并解析为JSON TO OBJECT (JObject)
        /// </summary>
        /// <returns></returns>
        protected JObject GetPostData(HttpContext context)
        {
            var jsonStr = "";
            using (var steam = new StreamReader(context.Request.InputStream))
            {
                jsonStr = steam.ReadToEnd();
            }
            return JObject.Parse(jsonStr);
        }

        /// <summary>
        /// (JSON)返回成功
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected void Success(HttpContext context, object data = null)
        {
            Reson(context, 1, data, "成功");
        }

        /// <summary>
        /// (JSON)返回错误
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected void erro(HttpContext context, object data = null)
        {
            Reson(context, 0, data, "异常");
        }

        /// <summary>
        /// (JSON)返回消息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        protected void Reson(HttpContext context, int code, object data, string msg)
        {
            if (msg == null)
            {
                msg = "";
            }
            var jObject = new JObject();
            jObject["Type"] = code;
            jObject["Msg"] = msg;
            if (data != null)
            {
                jObject["Data"] = JToken.FromObject(data);
            }
            context.Response.HeaderEncoding = Encoding.UTF8;
            context.Response.ContentType = "application/json";
            context.Response.Write(jObject.ToString());
            context.ApplicationInstance.CompleteRequest();
            //return  Content(, "", );
        }

        #endregion MyRegion

        /// <summary>
        /// 提交资金申请
        /// </summary>
        /// <returns></returns>
        public void SubmitApplay(HttpContext context)
        {
            var user = GetCurrentUser();
            var transactionBLL = new BLL.Lc_TransactionBLL();

            var data = GetPostData(context);
            var result = new JObject();
            result["Msg"] = "获取成功";
            result["Type"] = 1;
            switch (data["Type"].ToObject<string>())
            {
                case "Year":
                    {
                        #region 年

                        var year = data["Year"].ToObject<int>();
                        var companyId = data["CompanyId"].ToObject<int>();
                        var title = data["Title"].ToObject<string>();
                        var bzId = data["BzId"].ToObject<string>();
                        if (bzId == "")
                        {
                            Reson(context, 0, null, "请选择编制人");
                            return;
                        }
                        //查询年份是否已经申请资金计划。
                        var sql = "SELECT COUNT(1) FROM QX_PLANYEARAPPLY T1,SYS_USER T2 WHERE T1.N_USER_ID = T2.USER_ID AND T1.N_BUSINESS_STATE != 0 AND T1.N_YEAR=" + year.ToString() + " AND T2.USER_COMPANY = " + user.USER_COMPANY;
                        if (transactionBLL.GetCount(sql) > 0)
                        {
                            Reson(context, 0, null, year.ToString() + "年已发起资金申请,请不要重复发起");
                            return;
                        }
                        else
                        {
                            var bll = new QX_PLANYEARAPPLYBLL();
                            using (var conn = bll.GetDbConn())
                            {
                                conn.Open();
                                bll.Service.DbConnection = conn;
                                var businessBll = new Qs_BusinessBLL(bll.Service);
                                var companyBll = new Sys_CompanyBLL(bll.Service);
                                var processBll = new Lc_ProcessBLL(bll.Service);
                                var queueBll = new Lc_QueueBLL(bll.Service);
                                var conditionBll = new Lc_ConditionBLL(bll.Service);
                                var nodeBll = new Lc_NodeBLL(bll.Service);
                                var transactionBll = new Lc_TransactionBLL(bll.Service);
                                var projectBll = new QS_PROJECTBLL(bll.Service);
                                var planYearDetailsBll = new QX_PLANYEAR_DETAILBLL(bll.Service);
                                bll.BeginTran();
                                try
                                {
                                    var company = companyBll.GetInfoById(companyId.ToString());
                                    var process = processBll.GetProcessByCom("QX_PLANYEARAPPLY", user.USER_NAME);
                                    if (process == null)
                                    {
                                        result["Msg"] = "未设置年计划流程";
                                        result["Type"] = 0;
                                        break;
                                    }
                                    var business = new QS_Business();
                                    business.Business_Name = year.ToString() + "年计划编制（" + company.CMY_NAME + "）";
                                    business.Process_id = process.N_PROCESS_ID;// 121;
                                    business.Business_State = 1;
                                    business.Business_operator_Id = (int)user.USER_ID;
                                    business.Business_remark = title.Trim();
                                    business.N_COMPANY_ID = user.USER_COMPANY;
                                    business.Business_operator_date = DateTime.Now;
                                    businessBll.Insert(business);
                                    //新增主表
                                    var apply = new QX_PLANYEARAPPLY();
                                    apply.N_YEAR = year;
                                    apply.N_BUSINESS_ID = business.Business_Id;
                                    apply.C_YEARAPP_NAME = year.ToString() + "（" + company.CMY_NAME + "）";
                                    apply.N_COMPANY_ID = user.USER_COMPANY;
                                    apply.N_USER_ID = user.USER_ID;
                                    apply.C_REAMRK = title.Trim();
                                    apply.D_OPERATOR_TIME = DateTime.Now;
                                    apply.N_BUSINESS_STATE = business.Business_State;
                                    bll.Insert(apply);
                                    Lc_Transaction transaction = new Lc_Transaction();
                                    transaction.N_PROCESS_ID = business.Process_id;
                                    //获取第一步队列id
                                    transaction.N_QUEUE_ID = 171;
                                    transaction.N_business_id = business.Business_Id;
                                    transaction.C_TRANSACTION_COMMENT = "年计划申请";
                                    transaction.C_TRANSACTOR_ID = user.USER_ID.ToString();
                                    transaction.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
                                    transaction.D_TRANSACTION_TIME_END = DateTime.Now;
                                    transaction.D_TRANSACTION_TIME_DUE = DateTime.Parse("1900-1-1");
                                    transaction.N_TRANSACTION_STATE = 1;
                                    transaction.C_TRANSACTOR_SIGNATURE = "";
                                    transaction.N_LAST_BACE_TRANSACTION_ID = 0;
                                    transaction.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
                                    transaction.D_TRANSACTION_TIME_END = DateTime.Now;
                                    transactionBll.Insert(transaction);

                                    //添加子流程

                                    #region 并行

                                    Lc_Transaction nextTransaction = new Lc_Transaction();
                                    nextTransaction.N_PROCESS_ID = business.Process_id;
                                    nextTransaction.N_QUEUE_ID = 211;
                                    nextTransaction.N_business_id = business.Business_Id;
                                    nextTransaction.C_TRANSACTION_COMMENT = "";
                                    nextTransaction.C_TRANSACTOR_ID = bzId;
                                    nextTransaction.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
                                    nextTransaction.D_TRANSACTION_TIME_END = DateTime.Parse("1900-1-1");
                                    Lc_Queue queue = queueBll.GetInfoById(nextTransaction.N_QUEUE_ID.ToString());
                                    Lc_Node nodel = nodeBll.GetInfoById(queue.N_NODE_ID.ToString());
                                    nextTransaction.D_TRANSACTION_TIME_DUE = DateTime.Now.AddDays((int)nodel.N_DOIING_TIME);
                                    nextTransaction.N_TRANSACTION_STATE = 0;
                                    nextTransaction.C_TRANSACTOR_SIGNATURE = "";
                                    nextTransaction.N_LAST_BACE_TRANSACTION_ID = transaction.N_TRANSACTION_ID;
                                    transactionBll.Insert(nextTransaction);

                                    Lc_Transaction nextTransaction1 = new Lc_Transaction();
                                    nextTransaction1.N_PROCESS_ID = business.Process_id;
                                    nextTransaction1.N_QUEUE_ID = 212;
                                    nextTransaction1.N_business_id = business.Business_Id;
                                    nextTransaction1.C_TRANSACTION_COMMENT = "";
                                    nextTransaction1.C_TRANSACTOR_ID = "";
                                    nextTransaction1.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
                                    nextTransaction1.D_TRANSACTION_TIME_END = DateTime.Parse("1900-1-1");
                                    Lc_Queue queue1 = queueBll.GetInfoById(nextTransaction.N_QUEUE_ID.ToString());
                                    Lc_Node nodel1 = nodeBll.GetInfoById(queue.N_NODE_ID.ToString());
                                    nextTransaction1.D_TRANSACTION_TIME_DUE = DateTime.Now.AddDays((int)nodel.N_DOIING_TIME);
                                    nextTransaction1.N_TRANSACTION_STATE = 0;
                                    nextTransaction1.C_TRANSACTOR_SIGNATURE = "";
                                    nextTransaction1.N_LAST_BACE_TRANSACTION_ID = transaction.N_TRANSACTION_ID;
                                    transactionBll.Insert(nextTransaction1);
                                    //创建管理信息表数据
                                    planYearDetailsBll.LoadByApplyId((int)apply.N_YEARAPP_ID, (int)business.Business_Id);

                                    #endregion 并行

                                    bll.Commit(false);
                                    Success(context);
                                    return;
                                }
                                catch (Exception e)
                                {
                                    bll.Commit(true);
                                    Reson(context, 0, null, "申请失败");
                                    return;
                                }
                                finally
                                {
                                    if (bll.Tran != null)
                                    {
                                        bll.Commit(true);
                                    }
                                }
                            }
                            //var applyDetailBll = new QX_PLANYEAR_DETAILBLL(bll.Service);
                        }

                        #endregion 年
                    }
                case "Month":
                    {
                        #region 月

                        var date = data["Date"].ToObject<DateTime>();
                        var companyId = data["CompanyId"].ToObject<int>();
                        var title = data["Title"].ToObject<string>();
                        var bzId = data["BzId"].ToObject<string>();
                        QS_PLANMONTHAPPLY apply;
                        string msg;
                        var reson = new QS_PLANMONTHAPPLYBLL().Create(date, companyId, title, bzId.ToArry(), out apply, out msg);
                        if (!reson)
                        {
                            Reson(context, 0, null, msg);
                            return;
                        }
                        else
                        {
                            Success(context, new { Apply = apply });
                            return;
                        }

                        #endregion 月
                    }
                case "Week":
                    {
                        #region 周

                        var applyDate = data["Date"].ToObject<DateTime>();
                        var startDate = data["StartDate"].ToObject<DateTime>();
                        var endDate = data["EndDate"].ToObject<DateTime>();
                        var weekIndex = data["WeekIndex"].ToObject<int>();
                        var companyId = data["CompanyId"].ToObject<int>();
                        var title = data["Title"].ToObject<string>();
                        var bzId = data["BzId"].ToObject<string>();
                        QS_PLANWEEKAPPLY apply;
                        string msg;
                        var reson = new QS_PLANWEEKAPPLYBLL().Create(applyDate, weekIndex, startDate, endDate, companyId, title, bzId.ToArry(), out apply, out msg);
                        if (!reson)
                        {
                            Reson(context, 0, null, msg);
                            return;
                        }
                        else
                        {
                            Success(context, new { Apply = apply });
                            return;
                        }

                        #endregion 周
                    }
                default:
                    break;
            }
            //获取提交申请类型
            Success(context);
            return;
        }

        public void GetAllCompany(HttpContext context)
        {
            var comapnyBll = new Sys_CompanyBLL();
            var dt = comapnyBll.GetCompanyFatherAndChild(comapnyBll.User.USER_COMPANY);
            var jArry = new JArray();
            foreach (var item in dt.AsEnumerable())
            {
                var jObj = new JObject();
                jArry.Add(jObj);
                jObj["Id"] = item.GetValue<int>("CMY_ID").ToString();
                jObj["Name"] = item.GetValue<string>("CMY_NAME").ToString();
            }
            Success(context, jArry);
        }

        public void Save(HttpContext context)
        {
            var data = GetPostData(context);
            var type = data["Type"].ToObject<string>();
            switch (type)
            {
                case "YearDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = data["Data"] as JArray;
                        new QX_PLANYEAR_DEPARTMENTBLL().Update(userId, applyId, _data);
                        Success(context, _data);
                        return;
                    }
                case "Year":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        new QX_PLANYEARAPPLYBLL().Update(data["Data"] as JArray, applyId);
                        Success(context);
                        return;
                    }
                case "Week":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        new QS_PLANWEEKAPPLYBLL().Update(data["Data"] as JArray, applyId);
                        Success(context);
                        return;
                    }
                case "MonthDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = data["Data"] as JArray;
                        new QS_PLANMonth_DEPARTMENTBLL().Update(userId, applyId, _data);
                        Success(context, _data);
                        return;
                    }
                case "Month":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        new QS_PLANMONTHAPPLYBLL().Update(data["Data"] as JArray, applyId);
                        Success(context);
                        return;
                    }
                case "WeekDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = data["Data"] as JArray;
                        new QS_PLANWEEK_DEPARTMENTBLL().Update(userId, applyId, _data);
                        Success(context, _data);
                        return;
                    }
                default:
                    break;
            }
        }

        public void Get(HttpContext context)
        {
            var data = GetPostData(context);
            var type = data["Type"].ToObject<string>();
            switch (type)
            {
                case "YearDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QX_PLANYEAR_DEPARTMENTBLL().Exites(userId, applyId);
                        Success(context, _data);
                        return;
                    }
                case "YearHzLoad":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QX_PLANYEAR_DEPARTMENTBLL().GetHz(applyId);
                        Success(context, _data);
                        return;
                    }
                case "Year":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        Success(context);
                        return;
                    }
                case "YearHz":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QX_PLANYEAR_DETAILBLL().GetByYearID(applyId);
                        Success(context, _data);
                        return;
                    }
                case "GetDataByApplyId":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QX_PLANYEAR_DEPARTMENTBLL().GetDataByApplyId(applyId);
                        Success(context, _data);
                        return;
                    }
                case "MonthDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        //var _data = new QS_PLANMonth_DEPARTMENTBLL().Exites(userId, applyId);
                        var _data = new QS_PLANMonth_DEPARTMENTBLL().ExitesToJarray(userId, applyId);
                        Success(context, _data);
                        return;
                    }
                case "MonthHz":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        //var _data = new QS_PLANMONTH_DETAILBLL().GetByApplyId(applyId);GetByApplyIdToJArray
                        var _data = new QS_PLANMONTH_DETAILBLL().GetByApplyIdToJArray(applyId);
                        Success(context, _data);
                        return;
                    }
                case "WeekDepartment":
                    {
                        var userId = data["UserId"].ToObject<int>();
                        var applyId = data["ApplyId"].ToObject<int>();
                        //var _data = new QS_PLANWEEK_DEPARTMENTBLL().Exites(userId, applyId);
                        var _data = new QS_PLANWEEK_DEPARTMENTBLL().ExitesToJArray(userId, applyId);
                        Success(context, _data);
                        return;
                    }
                case "WeekHz":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        //var _data = new QS_PLANWEEK_DETAIL_BLL().GetByApplyId(applyId);
                        var _data = new QS_PLANWEEK_DETAIL_BLL().GetByApplyIdToJArray(applyId);
                        Success(context, _data);
                        return;
                    }
                case "MonthHzLoad":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QS_PLANMonth_DEPARTMENTBLL().GetHz(applyId);
                        Success(context, _data);
                        return;
                    }
                case "WeekHzLoad":
                    {
                        var applyId = data["ApplyId"].ToObject<int>();
                        var _data = new QS_PLANWEEK_DEPARTMENTBLL().GetHz(applyId);
                        Success(context, _data);
                        return;
                    }
                default:
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}